package com.computergames.server.protocol;

import com.computergames.server.message.Message;
import com.computergames.server.message.MoveRequestMessage;
import com.computergames.server.message.chessMessage.AbstractChessMessage;
import com.computergames.server.message.chessMessage.PerfectInformationGameMessage;
import com.computergames.server.message.chessMessage.ImperfectInformationGameMessage;
import com.computergames.server.message.chessMessage.GobangMessage;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

public class MoveRequestMessageTypeAdapter extends TypeAdapter<Message> {

    private final Gson gson;

    public MoveRequestMessageTypeAdapter(Gson gson) {
        this.gson = gson != null ? gson : new Gson(); // 如果传入为null，则创建一个新的默认Gson实例
    }

    @Override
    public void write(JsonWriter out, Message value) throws IOException {
        if (value == null) {
            out.nullValue();
            return;
        }

        if (value instanceof MoveRequestMessage) {
            MoveRequestMessage moveRequest = (MoveRequestMessage) value;

            out.beginObject();
            out.name("messageType").value(Message.MoveRequestMessage);
            out.name("from").value(moveRequest.getFrom());
            out.name("content");
            gson.toJson(moveRequest.getContent(), AbstractChessMessage.class, out); // 递归序列化content
            out.endObject();
        } else {
            // 这里可以添加对其他类型Message的处理逻辑
            throw new IllegalArgumentException("Unsupported message type: " + value.getClass().getName());
        }
    }

    @Override
    public Message read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
        }
        MoveRequestMessage message = new MoveRequestMessage();
        in.beginObject();
        while (in.hasNext()) {
            String name = in.nextName();
            switch (name) {
                case "messageType":
                    message.setMessageType(in.nextInt());
                    break;
                case "from":
                    message.setFrom(in.nextString());
                    break;
                case "content":
                    // 直接使用已经注册的TypeAdapter来解析content
                    message.setContent(gson.fromJson(in, AbstractChessMessage.class));
                    break;
                default:
                    in.skipValue();
            }
        }
        in.endObject();
        return message;
    }
}
